/* Filename: primer2.c
 * Description: 多进程,每个进程计算区间内1个数(并且等待回收进程)
 * Last modified: humble 20200322 17:05
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define LEFT (30000000)
#define RIGHT (30000200)

static void usage(void);

int main(int argc, char **argv) {
    if(argc != 1){ fprintf(stderr, "argc !=1"); usage(); exit(1); }
    int mark;
    pid_t pid;
    for(int i = LEFT; i < RIGHT; i++) {
        pid = fork();
        if(pid < 0){ perror("fork()"); exit(1); } // 创建失败
        else if(pid == 0){ // 子进程
            mark = 1;
            for(int j = 2; j < i/2; j++) {
                if(i % j == 0){ mark = 0; break; }
            }
            if(mark == 1){ printf("%d is a primer\n", i); }
            exit(0);
        }
        else{ continue; } // 父进程
    }

    //int st;
    for(int i = LEFT; i < RIGHT; i++) {
        // wait(&st); printf("%d\n", st); //等同waitpid(-1, &st, 0);
        wait(NULL); // 不关心返回状态用NULL 
    }
    return 0;
}

static void usage(void) {
#define USAGE "Usage:\n\
  Helloworld\n"
    printf(USAGE);
}
